package se.webbzon.boltzmann.game.sequence.builder.condition;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import se.webbzon.boltzmann.game.sequence.builder.SequenceBuilder;
import se.webbzon.boltzmann.game.sequence.builder.SequenceRowDeflation;
import se.webbzon.oschi01.friendly.Friendly;

public class ConditionRowDeflation implements SequenceRowDeflation {
	
	private ConditionEnum condition;
	
	private String lh, rh;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public ConditionRowDeflation() {};
	
	public ConditionRowDeflation(ConditionRow row) {
		this.condition = row.getCondition();
		this.lh = row.getLeftHandArgument();
		this.rh = row.getRightHandArgument();
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override public void inflate(ByteBuffer buff) {
		// Read from buffer
		condition = ConditionEnum.values()[buff.getInt()];
		byte[] lhData = new byte[buff.getShort()];
		buff.get(lhData, 0, lhData.length);
		byte[] rhData = new byte[buff.getShort()];
		buff.get(rhData, 0, rhData.length);
		
		// Decode strings
		try {
			lh = new String(lhData,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			lh = "";
		}
		
		try {
			rh = new String(rhData,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			rh = "";
		}
	}

	@Override public ByteBuffer deflate(int allocate) {
		byte[] lhData, rhData;
		
		// Encode strings
		try {
			lhData = lh.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			lhData = new byte[0];
		}
		
		try {
			rhData = rh.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			rhData = new byte[0];
		}
		
		ByteBuffer buff = ByteBuffer.allocate(allocate + 8 + rh.length() + lh.length());
		
		// Write to buffer
		buff.putInt(condition.ordinal());
		buff.putShort((short) lh.length());
		buff.put(lhData);
		buff.putShort((short) rh.length());
		buff.put(rhData);
		return buff;
	}
	
	/*============================================================
	Friendly Methods
	============================================================*/
	
	/** Returns the inflated condition row of this deflation. **/
	@Friendly ConditionRow makeRow(SequenceBuilder builder) {
		return new ConditionRow(builder,condition,lh,rh);
	}

}
